package com.txd.mofa.login;

import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bytedance.sdk.open.aweme.TikTokConstants;
import com.bytedance.sdk.open.aweme.TikTokOpenApiFactory;
import com.bytedance.sdk.open.aweme.api.TiktokOpenApi;
import com.bytedance.sdk.open.aweme.authorize.model.Authorization;
import com.kongzue.baseframework.interfaces.Layout;
import com.kongzue.baseframework.util.JumpParameter;
import com.kongzue.baseframework.util.Preferences;
import com.kongzue.baseokhttp.HttpRequest;
import com.kongzue.baseokhttp.listener.ResponseListener;
import com.kongzue.baseokhttp.util.Parameter;
import com.ninetaildemonfox.zdl.ninetails.map.JSONUtils;
import com. txd.mofa.MainActivity;
import com.txd.mofa.R;
import com.txd.mofa.base.BaseAty;
import com.txd.mofa.jiekou.FinishJishi;
import com.txd.mofa.net.NetUtils;
import com.txd.mofa.utils.CheckAppExist;
import com.txd.mofa.utils.VerificationTimer;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import cn.jpush.android.api.JPushInterface;
import cn.sharesdk.douyin.Douyin;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;

@Layout(R.layout.aty_login)
public class LoginAty extends BaseAty implements PlatformActionListener {

    private ImageView iv_denglu;
    private EditText et_shoujihao,et_yanzhengma;
    private ImageView iv_weixin,iv_qq,iv_weibo,iv_douyin;
    private TextView tv_yinsi,tv_xieyi,tv_yanzheng,tv_jishi;
    private VerificationTimer verificationTimer;
    private String head_pic;

    @Override
    public void initViews() {
        super.initViews();
        tv_jishi = findViewById(R.id.tv_jishi);
        tv_yanzheng = findViewById(R.id.tv_yanzheng);
        tv_yinsi = findViewById(R.id.tv_yinsi);
        tv_xieyi = findViewById(R.id.tv_xieyi);
        iv_weixin = findViewById(R.id.iv_weixin);
        iv_qq = findViewById(R.id.iv_qq);
        iv_weibo = findViewById(R.id.iv_weibo);
        iv_douyin = findViewById(R.id.iv_douyin);
        iv_denglu = findViewById(R.id.iv_denglu);
        et_shoujihao = findViewById(R.id.et_shoujihao);
        et_yanzhengma = findViewById(R.id.et_yanzhengma);

        //是否同意协议
        Preferences.getInstance().set(me,"tongyi","tongyi",1);

        et_shoujihao.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {



            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        et_yanzhengma.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() != 0 && s != null){
                    Glide.with(me).load(R.mipmap.denglu_huang).into(iv_denglu);
                }else {
                    Glide.with(me).load(R.mipmap.denglu_hei).into(iv_denglu);
                }
            }
        });

        verificationTimer = new VerificationTimer(60000, 1000, tv_jishi, "获取验证码", new FinishJishi() {
            @Override
            public void finish_jishi() {
                tv_jishi.setVisibility(View.GONE);
                tv_yanzheng.setVisibility(View.VISIBLE);
            }
        });

    }

    @Override
    protected void onNetworkConnected(NetUtils.NetType type) {

    }

    @Override
    protected void onNetworkDisConnected() {

    }

    @Override
    public void initDatas(JumpParameter paramer) {

    }

    private String open_type = "";

    @Override
    public void setEvents() {

        tv_yanzheng.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (et_shoujihao.getText().toString().equals("") || et_shoujihao.getText().toString() == null){
                    Toast.makeText(me, "手机号不能为空", Toast.LENGTH_SHORT).show();
                }else {
                    if (NetUtils.isNetworkAvailable(me)) {
                        sendVerify();
                    }else {
                        Toast.makeText(me, "网络连接错误，请检查您的网络", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });

        tv_xieyi.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (NetUtils.isNetworkAvailable(me)) {
                    jump(XieyiZhengceAty.class,new JumpParameter().put("pos",0).put("first","222"));
                }else {
                    Toast.makeText(me, "网络连接错误，请检查您的网络", Toast.LENGTH_SHORT).show();
                }


            }
        });
        tv_yinsi.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (NetUtils.isNetworkAvailable(me)) {
                    jump(XieyiZhengceAty.class,new JumpParameter().put("pos",1).put("first","222"));
                }else {
                    Toast.makeText(me, "网络连接错误，请检查您的网络", Toast.LENGTH_SHORT).show();
                }

            }
        });

        iv_denglu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (NetUtils.isNetworkAvailable(me)) {
                    if (et_shoujihao.getText().toString().equals("") || et_shoujihao.getText().toString() == null){
                        Toast.makeText(me, "手机号不能为空", Toast.LENGTH_SHORT).show();
                    }else {
                        if (et_yanzhengma.getText().toString().equals("") || et_yanzhengma.getText().toString() == null){
                            Toast.makeText(me, "验证码不能为空", Toast.LENGTH_SHORT).show();
                        }else {
                            login();
                        }
                    }
                }else {
                    Toast.makeText(me, "网络连接错误，请检查您的网络", Toast.LENGTH_SHORT).show();
                }


            }
        });

        iv_weixin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (NetUtils.isNetworkAvailable(me)) {
                    open_type = "2";
                    if (CheckAppExist.getInstancei().isAppAvilible(me, "com.tencent.mm")) {
                        Platform wx = ShareSDK.getPlatform(Wechat.NAME);
                        wx.removeAccount(true);
                        authorize(wx);
                    } else {
                        toast("请安装微信");
                    }
                }else {
                    Toast.makeText(me, "网络连接错误，请检查您的网络", Toast.LENGTH_SHORT).show();
                }

            }
        });
        iv_qq.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (NetUtils.isNetworkAvailable(me)) {
                    open_type = "1";
                    Platform qq = ShareSDK.getPlatform(QQ.NAME);
                    qq.removeAccount(true);
                    authorize(qq);
                }else {
                    Toast.makeText(me, "网络连接错误，请检查您的网络", Toast.LENGTH_SHORT).show();
                }

            }
        });
        iv_weibo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (NetUtils.isNetworkAvailable(me)) {
                    open_type = "3";
                    Platform weibo = ShareSDK.getPlatform(SinaWeibo.NAME);
                    weibo.removeAccount(true);
                    authorize(weibo);
                }else {
                    Toast.makeText(me, "网络连接错误，请检查您的网络", Toast.LENGTH_SHORT).show();
                }

            }
        });

        iv_douyin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (NetUtils.isNetworkAvailable(me)) {
                    open_type = "4";
                    Platform douyin = ShareSDK.getPlatform(Douyin.NAME);
                    douyin.removeAccount(true);
                    ShareSDK.setActivity(me);
                    authorize(douyin);
                }else {
                    Toast.makeText(me, "网络连接错误，请检查您的网络", Toast.LENGTH_SHORT).show();
                }



            }
        });

    }

    private void sendVerify() {
        HttpRequest.POST(me, sendVerify, new Parameter().add("account",et_shoujihao.getText().toString())
                .add("send_type","login"), new ResponseListener() {
            @Override
            public void onResponse(String response, Exception error) {
                if (error == null) {
                    Map<String, String> map = JSONUtils.parseKeyAndValueToMap(response);
                    Toast.makeText(me, map.get("message"), Toast.LENGTH_SHORT).show();
                    if (map.get("code").equals("1")){
                        verificationTimer.start();
                        tv_jishi.setVisibility(View.VISIBLE);
                        tv_yanzheng.setVisibility(View.GONE);
                    }
                }else {
                    toast("网络异常");
                }
            }
        });
    }

    private void login() {
        HttpRequest.POST(me, smsLogin, new Parameter().add("account",et_shoujihao.getText().toString()).add("verify",et_yanzhengma.getText().toString()), new ResponseListener() {
            @Override
            public void onResponse(String response, Exception error) {
                if (error == null) {
                    Map<String, String> map = JSONUtils.parseKeyAndValueToMap(response);
                    if (map.get("code").equals("1")){
                        Map<String, String> data = JSONUtils.parseKeyAndValueToMap(map.get("data"));

                        JPushInterface.setAlias(me, 1, data.get("token"));

                        Preferences.getInstance().set(me,"mofa","token",data.get("token"));

                        Preferences.getInstance().set(me,"face_img","face_img",data.get("face_img"));

                        jump(MainActivity.class);
                        finish();

                    }else {
                        Toast.makeText(me, map.get("message"), Toast.LENGTH_SHORT).show();
                    }
                }else {
                    toast("网络异常");
                }
            }
        });

    }

    public static int targetAppId = TikTokConstants.TARGET_APP.AWEME;//抖音

    private String openid = "";

    private void authorize(Platform plat) {
        // 授权监听
        plat.setPlatformActionListener(this);
        // true不使用SSO授权，false使用SSO授权，(即true不使用客户端登录，false有客户端则使用客户端登录，没有则使用web网页登录)
        plat.SSOSetting(false);
        // 获取用户资料
        plat.showUser(null);
    }

    @Override
    public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
        if (open_type.equals("2")) {
            openid = platform.getDb().get("unionid");
        } else {
            openid = platform.getDb().getUserId();
        }


        Log.e("openid", openid + ">>>>>>>>>");
        String nick = platform.getDb().getUserName();
        if (open_type.equals("4")){
            String data = platform.getDb().exportData();
            Map<String, String> map = JSONUtils.parseKeyAndValueToMap(data);
            head_pic = map.get("avatar");
        }else {
            head_pic = platform.getDb().getUserIcon();
        }

        HttpRequest.POST(me, threeLogin, new Parameter().add("only_id",openid)
                .add("nickname",nick)
                .add("head_pic", head_pic)
                .add("device_type","1")
                .add("login_type",open_type), new ResponseListener() {
            @Override
            public void onResponse(String response, Exception error) {
                if (error == null) {
                    Map<String, String> map = JSONUtils.parseKeyAndValueToMap(response);
                    if (map.get("code").equals("1")){
                        Map<String, String> data = JSONUtils.parseKeyAndValueToMap(map.get("data"));

                        JPushInterface.setAlias(me, 1, data.get("token"));

                        Preferences.getInstance().set(me,"mofa","token",data.get("token"));

                        Preferences.getInstance().set(me,"face_img","face_img",data.get("face_img"));

                        jump(MainActivity.class);
                        finish();
                    }

                }else {
                    toast("网络异常");
                }
            }
        });

    }

    @Override
    public void onError(Platform platform, int i, Throwable throwable) {

        Log.e("===============",throwable.getMessage());

        if (i == Platform.ACTION_USER_INFOR) {

        }
        throwable.printStackTrace();
    }

    @Override
    public void onCancel(Platform platform, int i) {
    }
}
